package com.dtf.admin.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.dtf.core.common.utils.Const;

public class JqGridFilter {
	
	class FilerRule{
		public String field;
		public String op;
		public String data;
		
		public Map getRuleReq(){
			List param = new ArrayList();
			String sql = "";
			if("eq".equals(op)){	//等于
				sql = field + " = ? ";
				param.add(data);
			}else if("ne".equals(op)){  	//不等　
				sql = field + " <> ? ";
				param.add(data);
			}else if("bw".equals(op)){ 	//开始于
				sql = field + " like ? ";
				param.add(data+"%");
			}else if("bn".equals(op)){ 	//不开始于
				sql = field + " not like ? ";
				param.add(data+"%");
			}else if("ew".equals(op)){ 	//结束于
				sql = field + " like ? ";
				param.add("%" + data);
			}else if("en".equals(op)){ 	//不结束于
				sql = field + " not like ? ";
				param.add("%" + data);
			}else if("cn".equals(op)){ 	//包含　　
				sql = field + " like ? ";
				param.add("%" + data + "%");
			}else if("nc".equals(op)){ 	//不包含
				sql = field + " not like ? ";
				param.add("%" + data + "%");
			}else if("nu".equals(op)){ 	//不存在
				sql = field + " is null ";
			}else if("nn".equals(op)){ 	//存在
				sql = field + " is not null ";
			}else if("in".equals(op)){ 	//属于　
				if(!StringUtils.isEmpty(data)){
					String[] strs = data.split(",");
					sql = field + " in (";
					for (String str : strs) {
						sql += "?,";
						param.add(str);
					}
					sql = sql.substring(0,sql.lastIndexOf(","));
					sql = sql + ") ";
				}
			}else if("ni".equals(op)){ 	//不属于
				if(!StringUtils.isEmpty(data)){
					String[] strs = data.split(",");
					sql = field + " not in (";
					for (String str : strs) {
						sql += "?,";
						param.add(str);
					}
					sql = sql.substring(0,sql.lastIndexOf(","));
					sql = sql + ") ";
				}
			}
			Map req = new HashMap();
			req.put("sql", sql);
			req.put("param", param);
			return req;
		}
		
	}
	
	//返回完整的条件SQL，只适合单表
	public Map getReq(){
		String sql = "";
		List param = new ArrayList();
		if (rules != null && rules.size() > 0 ) {
			for (FilerRule rule : rules) {
				Map ruleReq = rule.getRuleReq();
				sql += Const.getStrValue(ruleReq, "sql")  + " " + groupOp + " ";
				param.addAll((List)ruleReq.get("param"));
			}
			sql = sql.substring(0,sql.lastIndexOf(groupOp));
		}
		Map req = new HashMap();
		req.put("sql", sql);
		req.put("param", param);
		return req;
	}
	
	private String groupOp;
	private List<FilerRule> rules;
	
	public String getGroupOp() {
		return groupOp;
	}
	public void setGroupOp(String groupOp) {
		this.groupOp = groupOp;
	}
	public List<FilerRule> getRules() {
		return rules;
	}
	public void setRules(List<FilerRule> rules) {
		this.rules = rules;
	}
	
}
